#import "dfhgwhruebvhrheyoptionsaving.h"
#import "dfhgwhruebvhrheydenialnuisance.h"
#import "dfhgwhruebvhrheyoutwarddelegate.h"
#import "dfhgwhruebvhrheyluggagerecorder.h"
#import "UICKeyChainStore.h"
#import "dfhgwhruebvhrheysupposestern.h"
#import "dfhgwhruebvhrheymercyindependenceViewController.h"
#import "dfhgwhruebvhrheycandidateroutineViewController.h"
#import "dfhgwhruebvhrheyarrestmeans.h"
@implementation dfhgwhruebvhrheyoptionsaving
+ (dfhgwhruebvhrheyoutwarddelegate *)getUserData {
	NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingFormat:@"/%@",PPP_User_Info];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		NSData *data = [NSData dataWithContentsOfFile:filePath];
		NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		NSString *json = [base64String dhgfywegwygeydwappointmusician:dfhgwhruebvhrheyoptionsaving.uuid];
		dfhgwhruebvhrheyoutwarddelegate *model = [dfhgwhruebvhrheyoutwarddelegate yy_modelWithJSON:json];
		return model;
	}
	return nil;
}
+ (void)saveUserInfo:(NSString *)info completion:(void(^)(void))completion {
	NSString *jsonString = [info yy_modelToJSONString];
	NSString * userInfo = [jsonString dhgfywegwygeydwtextureappoint:dfhgwhruebvhrheyoptionsaving.uuid];
	NSData *data = [userInfo dataUsingEncoding:NSUTF8StringEncoding];
	NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingFormat:@"/%@",PPP_User_Info];
	if ([data writeToFile:filePath atomically:YES]) {
		if (completion) {
			completion();
		}
	}
}
+ (BOOL)isLogin {
	return [self getUserData] != nil;
}
+ (void)login:(void(^)(void))completion {
	UIWindow *key = [self keyWindow];
	if ([[key rootViewController] isKindOfClass:[dfhgwhruebvhrheycandidateroutineViewController class]]) {
		dfhgwhruebvhrheymercyindependenceViewController *loginVC = [[dfhgwhruebvhrheymercyindependenceViewController alloc] init];
		dfhgwhruebvhrheyarrestmeans *login = [[dfhgwhruebvhrheyarrestmeans alloc] initWithRootViewController:loginVC];
		login.modalPresentationStyle = UIModalPresentationFullScreen;
		dfhgwhruebvhrheycandidateroutineViewController *tabVC = (dfhgwhruebvhrheycandidateroutineViewController *)[key rootViewController];
		[tabVC presentViewController:login animated:YES completion:completion];
	}
}
+ (void)logout {
	NSError *error;
	NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingFormat:@"/%@",PPP_User_Info];
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
		if (error) {
			[[self keyWindow] show:@"failure"];
		}else {
			[[NSNotificationCenter defaultCenter] postNotificationName:PPP_LoginStatus object:nil];
		}
	}
}
+ (NSString *)uuid {
	UICKeyChainStore *keychain = [UICKeyChainStore keyChainStoreWithService:@"uuid_service"];
	NSString *uuidString = keychain[@"uuid"];
	if (uuidString == nil) {
		NSMutableString *m_uuidString = [UIDevice.currentDevice.identifierForVendor.UUIDString mutableCopy];
		NSRange range = [m_uuidString rangeOfString:@"-"];
		while (range.location != NSNotFound) {
			[m_uuidString replaceOccurrencesOfString:@"-" withString:@"" options:1 range:range];
			range = [m_uuidString rangeOfString:@"-"];
		}
		uuidString = m_uuidString;
		keychain[@"uuid"] = uuidString;
	}
	return uuidString;
}
+ (UIWindow *)keyWindow {
	if (@available(iOS 13.0, *)) {
		NSArray *arr = [[[UIApplication sharedApplication] connectedScenes] allObjects];
		UIWindowScene *windowScene = (UIWindowScene *)arr[0];
		return windowScene.windows.firstObject;
	}else {
		return [UIApplication sharedApplication].windows.lastObject;
	}
}
+ (BOOL)isValidToken:(NSInteger)code {
	NSArray *invalidStatus = @[@101, @102, @2001, @2002, @2003];
	BOOL isInvalid = [invalidStatus containsObject:@(code)];
	if (isInvalid) {
		if ([self getUserData]) {
			[[self keyWindow] show:@"Login status is invalid, please log in again."];
		}
		[self logout];
	}
	return isInvalid;
}
+ (NSString *)formatTime:(NSInteger)time WithDateFormat:(NSString *)format {
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	formatter.dateFormat = format;
	return [formatter stringFromDate:date];
}
+ (NSString *)appVersionString {
	NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
	return info[@"CFBundleShortVersionString"];
}
+ (void)saveDataString:(NSString *)dataString withKey:(NSString *)key {
	if ([self isLogin]) {
		NSString * encryString = [dataString dhgfywegwygeydwtextureappoint:dfhgwhruebvhrheyoptionsaving.uuid];
		NSData *data = [encryString dataUsingEncoding:NSUTF8StringEncoding];
		NSString *directoriyPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingFormat:@"/%@", [self getUserData].phone];
		if (![[NSFileManager defaultManager] fileExistsAtPath:directoriyPath]) {
			[[NSFileManager defaultManager] createDirectoryAtPath:directoriyPath withIntermediateDirectories:YES attributes:nil error:nil];
		}
		BOOL ret = [data writeToFile:[directoriyPath stringByAppendingFormat:@"/%@", key] atomically:YES];
		if (ret) {
			NSLog(@"数据保存成功");
		}
	}
}
+ (NSString *)getDataStringByKey:(NSString *)key {
	if ([self isLogin]) {
		NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingFormat:@"/%@/%@", [self getUserData].phone,key];
		if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
			NSData *data = [NSData dataWithContentsOfFile:filePath];
			NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
			NSString *dateString = [base64String dhgfywegwygeydwappointmusician:dfhgwhruebvhrheyoptionsaving.uuid];
			return dateString;
		}
		return nil;
	}
	return nil;
}
+ (NSString *)getRiskJsonData {
	dfhgwhruebvhrheydenialnuisance *model = [[dfhgwhruebvhrheydenialnuisance alloc] init];
	return [model yy_modelToJSONString];
}
+ (NSString *)currentTime {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSString *currentTime = [formatter stringFromDate:[NSDate date]];
	return currentTime;
}
+ (NSString *)loaderRiskDataBy:(NSString *)catchID withApplyId:(nullable NSString *)applyId andDetailId:(nullable NSString *)detailID {
	dfhgwhruebvhrheysupposestern *risk = [[dfhgwhruebvhrheysupposestern alloc] init];
	risk.apply_id = applyId;
	risk.detail_id = detailID;
	risk.device_id = [dfhgwhruebvhrheyoptionsaving uuid].dhgfywegwygeydwscholarshiptexture;
	risk.system_type = @"iOS";
	risk.apid = @"CASH_MATE";
	risk.version = [dfhgwhruebvhrheyoptionsaving appVersionString];
	risk.co_time = [self currentTime];
	risk.jdata = [self getRiskJsonData];
	NSMutableDictionary *dict = (NSMutableDictionary *)[risk yy_modelToJSONObject];
	dict[@"catch"] = catchID;
	return [dict yy_modelToJSONString];
}
+ (void)uploadRiskDataByCatchId:(NSString *)catchid andApplyId:(NSString *)applyId withDetailId:(NSString *)detailId {
	NSMutableDictionary *params = [NSMutableDictionary dictionary];
	dispatch_async(dispatch_get_global_queue(0, 0), ^{
		params[@"rdata"] = [self loaderRiskDataBy:catchid withApplyId:applyId andDetailId:detailId];
		[[dfhgwhruebvhrheyluggagerecorder shareInstance] ppp_fetchMethod:PPP_HttpMethodPost path:loadRiskDataApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
			dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
			if (model.code == 200) {
				NSLog(@"success");
			}else {
				[dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
			}
		} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
			NSLog(@"==== %@", error);
		}];
	});
}
@end
